package com.sentiment.servlet;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.bson.Document;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sentiment.bean.OperationInfo;
import com.sentiment.bean.RoleList;
import com.sentiment.database.bean.Permission;
import com.sentiment.database.bean.Role;
import com.sentiment.database.bean.Role_Permissions;
import com.sentiment.database.dbUtil.DbUtil;
import com.sentiment.tools.Paging;

/**
 * Servlet implementation class GetRolesInfo
 */
@WebServlet("/GetRolesInfo")
public class RolesInfoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
   
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		doPost(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		String methodName = request.getParameter("method");
		try{
			Method method = getClass().getMethod(methodName, 
					HttpServletRequest.class, HttpServletResponse.class);
			method.invoke(this, request, response);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取所有角色信息
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void GetRolesList(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
						
		int page  = Integer.parseInt(request.getParameter("pagenum"));
		List<RoleList> roles = new ArrayList<>();
		RoleList role = new RoleList();
		roles = role.getRoleList(page, 10);
		long count = role.getCount();
		
		ObjectMapper mapper = new ObjectMapper();
		String jsonArr = mapper.writeValueAsString(roles);
		String jsonStr = "";
		if(count != 0){
			jsonStr = "{\"recordsTotal\":"+ count +",\"RolesInfo\":" + jsonArr+"}";
		}else{
			jsonStr = "{\"recordsTotal\":"+ count +",\"Info\":" + "\"" + OperationInfo.NoRoles + "\"" +"}";
		}
		System.out.println(jsonStr);
		
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(jsonStr);
	}
	
	
	
	/**
	 * 角色添加一个权限
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void AddPer(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		String role_id = request.getParameter("role_id");
		String per_id = request.getParameter("per_id");
		
		
		Role role = new Role();
		role = role.getRoleByRoleId(role_id);
		String info = "";
		if(role != null){			
			Permission per = new Permission();
			per = per.getPermissionByPermissionId(per_id);
			if(per != null){
				info = role.addPer(per_id);
			}else{
				info = OperationInfo.OperFailure;
			}
		}else{
			info = OperationInfo.OperFailure;
		}
		
		String jsonStr = "{\"Info\":" + "\"" + info + "\"" +"}";
		
		System.out.println(jsonStr);
		
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(jsonStr);
	}
	
	
	/**
	 * 角色移除一个权限
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void RemovePer(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		String role_id = request.getParameter("role_id");
		String per_id = request.getParameter("per_id");
		
		
		Role role = new Role();
		role = role.getRoleByRoleId(role_id);
		String info = "";
		if(role != null){			
			Permission per = new Permission();
			per = per.getPermissionByPermissionId(per_id);
			if(per != null){
				info = role.removePer(per_id);
			}else{
				info = OperationInfo.OperFailure;
			}
		}else{
			info = OperationInfo.OperFailure;
		}
		
		String jsonStr = "{\"Info\":" + "\"" + info + "\"" +"}";
		
		System.out.println(jsonStr);
		
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(jsonStr);
	}
	
	
	
	/**
	 * 查找
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void Query(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		String role_detail = request.getParameter("role_detail");		
		String permission_detail = request.getParameter("permission_detail");
		int page  = Integer.parseInt(request.getParameter("pagenum"));
		
		DbUtil db = new DbUtil();
		String info = "";
		String role_id = "";
		if(!role_detail.equals("")){
			Role role = new Role();
			role = role.getRoleByRole_detail(role_detail);
			if(role != null){
				role_id = role.get_id();
			}else{
				info = OperationInfo.NoSuchRole;
			}
		}
		
		List<String> listroleid = new ArrayList<>();
		if(!permission_detail.equals("")){
			Permission permission = new Permission();
			permission = permission.getPermissionByPermission_detail(permission_detail);
			if(permission != null){
				List<Document> tlist = new ArrayList<>();
				db.openConnection(Role_Permissions.dbName, Role_Permissions.collection);
				tlist = db.queryByOneinList("permission_id", permission.get_id());
				db.closeConnection();
				if(tlist.size() == 0){
					info = OperationInfo.NoSuchRole;
				}else{
					for (int i = 0; i < tlist.size(); i++) {
						Role_Permissions role_pers = new Role_Permissions(tlist.get(i));
						listroleid.add(role_pers.getRole_id());
					}
				}				
			}else{
				info = OperationInfo.NoSuchRole;
			}
		}
		
		//合并结果
		String jsonStr = "";
		
		if(info.equals("")){
			if(!role_id.equals("")){
				if(listroleid.size() == 0){
					listroleid.add(role_id);
				}else{
					if(listroleid.contains(role_id)){
						listroleid.retainAll(Arrays.asList(role_id));
					}else{
						jsonStr = "{\"recordsTotal\":"+ 0 +",\"Info\":" + "\"" + OperationInfo.NoSuchRole + "\"" +"}";
					}
				}
			}
			if(jsonStr.equals("")){
				List<RoleList> listrolelist = new ArrayList<>();
				RoleList rolelist = new RoleList();
				long count = listroleid.size();
				listroleid = Paging.pagingStr(listroleid, page, 10);
				for (int i = 0; i < listroleid.size(); i++) {
					Role_Permissions role_pers = new Role_Permissions();
					role_pers = role_pers.getRole_PermissionsByRole_id(listroleid.get(i));				
					rolelist = rolelist.getRoleListByRole_pers(role_pers);
					listrolelist.add(rolelist);
				}
				
				ObjectMapper mapper = new ObjectMapper();
				String jsonArr = mapper.writeValueAsString(listrolelist);
				jsonStr = "{\"recordsTotal\":"+ count +",\"RolesInfo\":" + jsonArr+"}";
			}
			
		}else{
			jsonStr = "{\"recordsTotal\":"+ 0 +",\"Info\":" + "\"" + info + "\"" +"}";
		}			
		
		
		System.out.println(jsonStr);
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(jsonStr);
	}
}
